#Author: Tanyong
# *-* coding:utf8 *-*
# @time       : 18-7-16 下午7:59
# @Author     : Tanyong
# @Site       : 
# @File       : views.py
# @Software   : PyCharm
from flask import current_app
from flask import flash
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for

from . import home
from info.Models import Info, db
from info.Models import Focus

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired



# @home.route('/', methods=['GET'])
# def index():
#     """首页"""
#     data_Info = Info.query.all()
#     return render_template("home/index.html", datainfo=data_Info)

@home.route('/')
def index():
    """首页"""
    page = request.args.get("page", 1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news = []
    current_page = 1
    total_page = 1

    try:
        paginate = Info.query.paginate(page, 10)
        news = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    # 进行模型列表转字典列表
    user_dict_li = []
    for user in news:
        user_dict_li.append(user)

    data = {
        "news": user_dict_li,
        "total_page": total_page,
        "current_page": current_page,
    }

    return render_template('home/index.html', data=data)

@home.route('/center', methods=['GET'])
def center():
    """个人中心"""
    data_Focus = Focus.query.all()
    return render_template("home/center.html", datainfo=data_Focus)

@home.route('/add_focus/<id>')
def add_focus(id):
    """添加股票关注"""
    exitence = Focus.query.filter(Focus.info_id==id).first()
    # 1. 先判断是否已经关注过此股票， 如果已经关注则无需重复关注
    if exitence:
        flash('已经关注过此股票了，不用重复关注！')
    else:
        focus_add = Focus(info_id= id)

        try:
            db.session.add(focus_add)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(e)
            flash("添加股票关注失败！")
    return redirect(url_for('home.index'))


@home.route('/del/<id>')
def delete(id):
    """取消股票关注"""
    focu_info = Focus.query.filter(Focus.id == id).first()
    # 1. 先查询是否有这只股票，如果没有则 无法取消关注
    if not focu_info:
        flash("没有这个股票" )
    else:
        try:
            db.session.delete(focu_info)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(e)
            flash("取消股票关注失败！")

    return redirect(url_for('home.center'))

@home.route('/upgrade/<id>', methods= ["GET", "POST"])
def upgarde(id):
    """修改关注股票备注"""
    info = Focus.query.filter(Focus.id == id).first()

    class InfoUpdateForm(FlaskForm):
        note_info = StringField(label=info.infos.code+"-备注信息", validators=[DataRequired("请输入股票备注信息")], default=info.note_info)
        submit = SubmitField('保存')

    form = InfoUpdateForm()

    if form.validate_on_submit():
        data = form.data
        info.note_info=data['note_info']

        db.session.commit()
        flash("修改股票备注信息成功！", "ok")
        return redirect(url_for('home.center'))
    return render_template('home/update.html', form=form)